<?php
/**
* @version 1.5.x
* @package JoomVision Project
* @email webmaster@joomvision.com
* @copyright (C) 2008 http://www.JoomVision.com. All rights reserved.
*/
// no direct access
defined ( '_JEXEC' ) or die ( 'Restricted access' );
$user = &JFactory::getUser ();
$db = &JFactory::getDBO ();

require_once (JPATH_SITE . DS . 'components' . DS . 'com_content' . DS . 'helpers' . DS . 'route.php');

class modJvTabs extends JObject {
	//var $_modulename        =	"";
	var $_moduleID = "";
	var $_categoryID = "";
	var $_view = "";
	var $_title_type = "";
	var $_thumb_size = "";
	var $_intro_lenght = "";
	var $_thumb_display = "";
	/** @var int */
	var $_Height = 'auto';
	/** @var int */
	var $_Width = '100%';
	/** @var string */
	var $_position = "top";
	/** @var int */
	var $_tHeight = 30;
	/** @var int */
	var $_tWidth = 120;
	/** @var string */
	var $_type = "content";
	/** @var string */
	var $_mposition = "left";
	/** @var string */
	var $_content = "";
	/** @var string */
	var $_result = "";
	/** @var string */
	var $_animType = "animMoveLeft"; //animMoveLeft, animFade, animMoveDown
	/** @var string */
	var $_mouseType = "click"; //click, mouseove
	/** @var string */
	var $_style = ""; 
	/** @var int */
	var $_duration = 100;	
	/** @var int */
	var $_maxitem = 5;
	/** @var int */
	var $_leadingCount = 1;
	/** @var int */
	var $_showReadMore = 0;
	/** @var string */
	var $_readMoreText = 'read more...';
	
	var $_odering;
	function __construct($params) {
		
		$this->_style = $params->get ( 'style', $this->_style );
		
		$this->_Height = $params->get ( 'Height', $this->_Height );
		
		$this->_Width = $params->get ( 'Width', $this->_Width );
		
		$this->_position = $params->get ( 'position', $this->_position );
		
		$this->_tHeight = $params->get ( 'tHeight', $this->_tHeight );
		
		$this->_tWidth = $params->get ( 'tWidth', $this->_tWidth );
		
		$this->_type = $params->get ( 'type', $this->_type );
		
		$this->_view = $params->get ( 'categoryID-view', $this->_view );

		$this->_title_type = $params->get ( 'categoryID-link', $this->_title_type );

		$this->_thumb_size = $params->get ( 'thumb_size', $this->_thumb_size );

		$this->_intro_lenght = $params->get ( 'intro_lenght', $this->_intro_lenght );

		$this->_thumb_display = $params->get ( 'thumb_display', $this->_thumb_display );
		
		$this->_mposition = $params->get ( 'moduleID-position', $this->_mposition );
		
		//		$this->_content = $params->get('content-content',$this->_content);
		

		$this->_animType = $params->get ( 'animType', $this->_animType );
		
		$this->_mouseType = $params->get ( 'mouseType', $this->_mouseType );
		
		$this->_duration = $params->get ( 'duration', $this->_duration );			
		
		$this->_moduleID = $params->get ( 'moduleID-list', $this->_moduleID );
		
		$this->_categoryID = $params->get ( 'categoryID-list', $this->_categoryID );
		
		$this->_maxitem = ( int ) $params->get ( 'categoryID-maxItem', 5 );
		
		$this->_leadingCount = ( int ) $params->get ( 'categoryID-leading_count', 1 );
		
		$this->_showReadMore = ( int ) $params->get ( 'categoryID-readmore', 0 );
		
		$this->_readMoreText = trim ( $params->get ( 'categoryID-readmoreText', 'read more...' ) );
		
		$this->_odering = $params->get ( 'categoryID-ordering' );
	}
	
	function Jvtabs_PrepareSettings() {
		global $mainframe;
		
		$hs_base = JURI::base () . 'modules/mod_jvtabnews/assets/';
		$headtag = array ();
		$headtag [] = "<script type='text/javascript' src='" . $hs_base . "jv_tabs.js' charset=\"utf-8\"></script>";
		$headtag [] = JHTML::_ ( 'behavior.mootools' );
		
		echo "<script type=\"text/javascript\">
				<!--
				/* <![CDATA[ */
					new Asset.css('" . $hs_base . "jv_tabs.css', {id: 'myTabs', title: 'myTabs'});
				/* ]]> */
				-->
			</script>";
		
		$mainframe->addCustomHeadTag ( implode ( "\n", $headtag ) );
	}
	
	function getString() {
		if ($this->_categoryID || $this->_moduleID) {
			$this->Jvtabs_PrepareSettings ();
			switch ($this->_type) {
				case "moduleID" :
					$row->text = $this->parseTabModuleID ();
					break;
				case "categoryID" :
				default :
					$row->text = $this->parseTabArticle ();
					break;
			}
			
			return $row->text;
		} else
			return "";
	}
	
	function parseTabModuleID() {
		$lis = '';
		$divs = '';
		if ($this->_moduleID != '')
			$list_moduleID = split ( ",", $this->_moduleID );
		$modules = & JModuleHelper::_load ();
		for($n = 0; $n < count ( $modules ); $n ++) {
			for($i = 0; $i < count ( $list_moduleID ); $i ++) {
				if ('mod_jvtabnews' != $list_moduleID [$i]) {
					$id = $list_moduleID [$i];
					$module = $modules [$n];
					if ($module && ($module->id == $id)) {
						$lis .= "<li title=\"" . $module->module . "\"><h3><span>" . $module->title . "</span></h3></li>";
						$divs .= "<div  class=\"jv-tab-content\">
								<div class=\"jv-tab-subcontent\">";
						$divs .= JModuleHelper::renderModule ( $module );
						$divs .= '  </div>
							 </div>';
					}
				}
			}
		}
		if ($lis != '') {
			return $this->writeTabs ( $lis, $divs );
		}
		return '';
	}
	
	function parseTabArticle() {
		$list = null;
		$lis = '';
		$divs = '';
		if ($this->_categoryID) {
			$list = $this->getList ( '', $this->_categoryID, 0 );
		}

		$list_cat = $this->getListCategory ();
		
		if ($list_cat) {
			$w = 0;
			foreach ( $list_cat as $cat ) {
				$w ++;
				$lis .= "<li title=\"" . $cat->title . "\"><h3><span>" . $cat->title . "</span></h3></li>";
				$divs .= "<div  class=\"jv-tab-content\">";
				$numItem = 0;
				foreach ( $list as $row ) {
					if ($row->catid == $cat->id) {
						if ($numItem >= $this->_maxitem)
							break;

						$classCount = "";
						if($numItem == 0)
							$classCount = "itemfirst";
						elseif($numItem > count($row))
							$classCount = "itemlast";

						$divs .= "<ul><li title=\"" . $row->title . "\" class=\"" . $classCount . "\">";
					
						if($this->_title_type == "link")
							$divs .= "<h3><a href='" . $row->link. "' title=\"" . $row->title . "\">" . $row->title . "</a></h3>";
						else
							$divs .= "<h3><a href='javascript:void(0);' onclick='ShowHideDiv(\"jv-tab-cat_" . $row->id . "\")'>" . $row->title . "</a></h3>";

						$divs .= "<div id= 'jv-tab-cat_" . $row->id . "' class=\"jv-tab-subcontent\" style=\"display: " . ($numItem < $this->_leadingCount ? "block" : "none") . "\">";
						$divs .= "<table style=\"margin:0px; padding:0px; width:auto;\">";
						$divs .= "<tr><td>";

						if($this->_thumb_display == "display" ){
							if (function_exists("gd_info")){
								$divs .= "<a href='" . $row->link. "' title=\"" . $row->title . "\"><img src=\"". $row->thumb . "\" align=\"left\" alt=\"" . $row->title . "\" /></a>";
							}
							else{
								$divs .= "<a href='" . $row->link. "' title=\"" . $row->title . "\"><img src=\"". $row->thumb . "\" width=\"" . $this->_thumb_size . "\" align=\"left\" alt=\"" . $row->title . "\" /></a>";
							}
						}

						$divs .= $row->introtext;
						if($this->_view == 'fulltext'){ $divs .= $row->fulltext; }
						$divs .= "</td></tr>";
						if ($this->_showReadMore == 1 && $this->_view == "introtext") {
							$divs .= "<tr><td>";
							$divs .= "<a href='" . $row->link . "' class='readon'>" . $this->_readMoreText . "</a>";
							$divs .= "</td></tr>";
						}
						$numItem ++;
						$divs .= "</table>";
						$divs .= '</div></li></ul>';
					}
				}
				$divs .= '</div>';
			}
			return $this->writeTabs ( $lis, $divs );
		}
		return '';
	}
	
	function writeTabs($lis, $divs) {
		global $mainframe;
		
		if (! defined ( "JVTAB_HEADTAG_" . strtoupper ( $this->_style ) )) {
			$headtag [] = '<link rel="stylesheet" href="' . JURI::base () . 'modules/mod_jvtabnews/assets/themes/' . $this->_style . '/style.css" type="text/css" media="screen"/>';
			$mainframe->addCustomHeadTag ( implode ( "\n", $headtag ) );
			define ( "JVTAB_HEADTAG_" . strtoupper ( $this->_style ), true );
		}
		
		$id = 'myTab-' . rand ();
		
		$html = '';
		$style = 'style="';
		if (is_numeric ( $this->_Height ) && $this->_Height > 0) {
			$style .= 'height:' . $this->_Height . 'px;';
		}
		if (is_numeric ( $this->_Width ) && $this->_Width > 0) {
			$style .= 'width:' . $this->_Width . 'px;';
		} else {
			$style .= 'width:100%;';
		}
		$style .= '"';
		
		$html .= '<div class="jv-tabswrap ' . strtolower ( $this->_style ) . '" ' . $style . '>';
		
		$html .= '	<div  id="' . $id . '" class="container" >';
		
		if ($this->_position == 'top') {
			/* set style for title top */
			$styleTop = 'style="';
			if (is_numeric ( $this->_tHeight ) && $this->_tHeight > 0) {
				$styleTop .= 'height:' . $this->_tHeight . 'px;';
			}
			$styleTop .= '"';
			
			$html .= '	<div class="jv-tabs-title-' . $this->_position . '" ' . $styleTop . '>';
		} elseif ($this->_position != 'bottom') {
			/* set style for title top */
			$styleMiddle = 'style="';
			
			if (is_numeric ( $this->_tWidth ) && $this->_tWidth > 0) {
				$styleMiddle .= 'width:' . $this->_tWidth . 'px;';
			} else {
				$styleMiddle .= 'width:' . $this->_tWidth . ';';
			}
			$styleMiddle .= '"';
			
			$html .= '	<div class="jv-tabs-title-' . $this->_position . '" ' . $styleMiddle . '>';
		}
		
		$style = '';
		if (is_numeric ( $this->_Height ) && $this->_Height > 0) {
			$style = 'style="height:0px;"';
		}
		
		if ($this->_position == 'bottom') {
			$html .= '<div class="jv-tab-panels-' . $this->_position . '" ' . $style . '>' . $divs . '</div>
							<div class="jv-tabs-title-' . $this->_position . '" >			
								<ul class="jv-tabs-title">' . $lis . '</ul>
							 </div>						
							';
		} else {
			$html .= '
								<ul class="jv-tabs-title">' . $lis . '</ul>
							</div>						
							<div class="jv-tab-panels-' . $this->_position . '" >' . $divs . '</div>';
		}
		
		$html .= '	</div>
					</div>';
		$html .= '<script type="text/javascript" charset="utf-8">
					<!--
					/* <![CDATA[ */
						window.addEvent("load", init);
						function init() {
							myTabs1 = new JVTabs("' . $id . '", {' .
							'position:\''.$this->_position.'\','. 
							'width:\''.$this->_Width.'\','.
							'height:\''.$this->_Height.'\','.
							'skipAnim:false,'.
							'animType:\''.$this->_animType.'\','.
							'mouseType:\''.$this->_mouseType.'\','.
							'fixheight:'.$this->_tHeight.','.
							'fixwidth:'.$this->_tWidth.','.
							'position:\''.$this->_position.'\''.														
							'});							
						}
						/* ]]> */
						-->
				     </script>';
		return $html;
	}
	
	//category functions:
	function getList($ids = '', $catid = '', $limit = 0) {
		$db = & JFactory::getDBO ();
		$user = & JFactory::getUser ();
		$aid = $user->get ( 'aid', 0 );
		
		$contentConfig = &JComponentHelper::getParams ( 'com_content' );
		$noauth = ! $contentConfig->get ( 'shownoauth' );
		
		jimport ( 'joomla.utilities.date' );
		$date = new JDate ( );
		$now = $date->toMySQL ();
		switch ($this->_odering) {
			case 'm_dsc' :
				$ordering = 'a.modified DESC, a.created DESC';
				break;
			case 'c_dsc' :
				$ordering = ' ORDER BY a.ordering ';
				break;
			default :
				$ordering = 'a.ordering';
				break;
		}
		$nullDate = $db->getNullDate ();
		
		// query to determine article count
		$query = 'SELECT a.*,a.id as key1, cc.id as key2, cc.title as cat_title, ' . ' CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug,' . ' CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(":", cc.id, cc.alias) ELSE cc.id END as catslug' . ' FROM #__content AS a' . ' INNER JOIN #__categories AS cc ON cc.id = a.catid' . ' INNER JOIN #__sections AS s ON s.id = a.sectionid';
		$query .= ' WHERE a.state = 1 ' . ($noauth ? ' AND a.access <= ' . ( int ) $aid . ' AND cc.access <= ' . ( int ) $aid . ' AND s.access <= ' . ( int ) $aid : '') . ' AND (a.publish_up = ' . $db->Quote ( $nullDate ) . ' OR a.publish_up <= ' . $db->Quote ( $now ) . ' ) ' . ' AND (a.publish_down = ' . $db->Quote ( $nullDate ) . ' OR a.publish_down >= ' . $db->Quote ( $now ) . ' )' . ' AND cc.section = s.id' . ' AND cc.published = 1' . ' AND s.published = 1';
		if ($ids != '') {
			$query .= "\n AND a.id in ($ids)";
		}
		if ($catid != '') {
			//$query .=	" AND a.catid=$catid";
			$ids = explode ( ',', $catid );
			JArrayHelper::toInteger ( $ids );
			$query .= ' AND (a.catid=' . implode ( ' OR a.catid=', $ids ) . ')';
		}
		$query .= ' ORDER BY ' . $ordering;
		if ($catid != '' && $limit > 0) {
			$query .= (' LIMIT ' . $limit);
		}
		
		$db->setQuery ( $query );
		$row = $db->loadObjectList ();

		$i		= 0;
		foreach ( $row as $lists )
		{
			$rows[$i]->id = $lists->id;
			$rows[$i]->thumb = modJvTabs::getThumb($lists->introtext, $this->_thumb_size);
			$rows[$i]->catid = $lists->catid;
			$rows[$i]->created = $lists->created;
			$rows[$i]->modified = $lists->modified;
			$rows[$i]->link = JRoute::_(ContentHelperRoute::getArticleRoute($lists->slug, $lists->catslug, $lists->sectionid));
			$rows[$i]->title = htmlspecialchars( $lists->title );
			$rows[$i]->introtext = modJvTabs::introContent( $lists->introtext, $this->_intro_lenght);
			$i++;
		}
		//for($i = 0; $i < count ( $rows ); $i ++) {
		//	$rows [$i]->text = $rows [$i]->introtext;
		//	$rows [$i]->introtext = $rows [$i]->text;
		//}

		return $rows;
	
	}
	
	function getListCategory() {
		$db = & JFactory::getDBO ();
		
		if ($this->_categoryID) {
			$sql = "SELECT * FROM #__categories " . "WHERE id IN (" . $this->_categoryID . ")";
			$db->setQuery ( $sql );
			$rows = $db->loadObjectList ();
		}
		
		$list_category = $rows;
		return $list_category;
	}

	function getThumb($text, $size, $reflections=false) {

		preg_match("/\<img.+?src=\"(.+?)\".+?\/>/", $text, $matches);
		$paths = array();
		if (isset($matches[1])) {
			$image_path = $matches[1];

			//joomla 1.5 only
			$full_url = JURI::base();
			
			//remove any protocol/site info from the image path
			$parsed_url = parse_url($full_url);
			
			$paths[] = $full_url;
			if (isset($parsed_url['path']) && $parsed_url['path'] != "/") $paths[] = $parsed_url['path'];
			
			
			foreach ($paths as $path) {
				if (strpos($image_path,$path) !== false) {
					$image_path = substr($image_path,strpos($image_path, $path)+strlen($path));
				}
			}
			
			// remove any / that begins the path
			if (substr($image_path, 0 , 1) == '/') $image_path = substr($image_path, 1);
			
			//if after removing the uri, still has protocol then the image
			//is remote and we don't support thumbs for external images
			if (strpos($image_path,'http://') !== false ||
				strpos($image_path,'https://') !== false) {
				return false;
			}
			
			// create a thumb filename
			$file_div = strrpos($image_path,'.');
			$thumb_ext = substr($image_path, $file_div);
			$thumb_prev = substr($image_path, 0, $file_div);
			$thumb_path =  $thumb_prev . "_tabnews_thumb" . $thumb_ext;
			// check to see if this file exists, if so we don't need to create it
			if (function_exists("gd_info") && !file_exists($thumb_path)) {
				// file doens't exist, so create it and save it
				include_once('thumbnail.inc.php');
				$thumb = new Thumbnail($image_path);
				
				if ($thumb->error) { 
					if (MININEWS_DEBUG)	echo "JVSECTCONT ERROR: " . $thumb->errmsg . ": " . $image_path; 
					return false;
				}
				$thumb->resize($size);
				if ($reflections) {
					$thumb->createReflection(30,30,60,false);
				}
				if (!is_writable(dirname($thumb_path))) {
					$thumb->destruct();
					return false;
				}
				$thumb->save($thumb_path);
				$thumb->destruct();
			}
			return ($thumb_path);
		} else {
			return false;
		}
	}

	function introContent( $text, $length=200 ) {
		$text = preg_replace( "'<script[^>]*>.*?</script>'si", "", $text );
		$text = preg_replace( '/{.+?}/', '', $text);
		$text = strip_tags(preg_replace( "'<(br[^/>]*?/|hr[^/>]*?/|/(div|h[1-6]|li|p|td))>'si", ' ', $text ));
		if (strlen($text) > $length) {
			$text = substr($text, 0, strpos($text, ' ', $length)) . "..." ;
		} 
		return $text;
	}

}
?>
